﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EnvDTE;
using System.IO;
using System.Windows.Forms;
using System.Xml;

namespace RuleCode.ObjectTree
{
    #region 插件工具类 Util_DTE
    /// <summary>
    /// 插件相关的工具类
    /// </summary>
    public  class Util_DTE
    {
        public static string AddName { get; set; }

        #region LabelFile,AOTFile版本控制相关
        public  static Dictionary<FileVersionType, Struct_GenerateTypePathProject> AllFileVersionStruct;
        //public static Dictionary<FileVersionType, Struct_GenerateTypePathProject> AllFileVersionStruct
        //{
        //    get {
        //        if (_AllFileVersionStruct == null)
        //            Util.InitCurrentProfileName();
        //        return _AllFileVersionStruct;
        //    }
        //    set
        //    {
        //        _AllFileVersionStruct = value;
        //    }
        //}
        #endregion

        #region 设置属性
        /// <summary>
        /// 获取或设置  编译之后就将文件添加到项目中
        /// </summary>
        public static bool IsAddToProjectAtCompiled
        {
            get;
            set;
        }

        /// <summary>
        /// 获取或设置 是否将LabelFile和AOTFile加入项目中以进行版本控制
        /// </summary>
        public static bool IsAddLabelAndAOTToSolution
        {
            get;
            set;
        }

        /// <summary>
        /// 获取或设置 AOTFile将要添加到的项目
        /// </summary>   
        public static Project GetAOTFileProject
        {
            get;
            set;
        }

        /// <summary>
        /// 获取或设置 AOTFile将要添加到的项目对应的路径
        /// </summary>
        public static string GetAOTFileProjectPath
        {
            get;
            set;
        }

        /// <summary>
        /// 获取或设置 编译表的时候就编译 Form,Web,和Query
        /// </summary>
        public static bool IsFormAndQueryCompileWithTable
        {
            get;
            set;
        }

        /// <summary>
        /// 获取或设置 生成数据层类文件存放在项目中对应的路径 ,包含"\\"
        /// 其中存放 Table,Query,TableField,ExtendDataType,Enum ,Class
        /// </summary>
        public static string BasePath_ClassFile
        {
            get;
            set;
        }
        /// <summary>
        /// 获取或设置 生成Web类文件存放在项目中对应的路径,包含"\\"
        /// 其中存放 WebForm
        /// </summary>
        public static string BasePath_WebFile
        {
            get;
            set;
        }
        /// <summary>
        /// 获取或设置 生成Form类文件存放在项目中对应的路径 ,包含"\\"
        /// 其中存放 Form 窗体
        /// </summary>
        public static string BasePath_FormFile
        {
            get;
            set;
        }


        /// <summary>
        /// 获取或设置 安装文件的路径 包含"\\"
        /// </summary>
        public static string AddIn_SetUpPath
        { get; set; }

        /// <summary>
        /// 获取解决模板总路径
        /// </summary>
        public static string TemplatePath_Solutions
        {
            get { return AddIn_SetUpPath +"Templates\\Solutions\\";}
        }

        /// <summary>
        /// 获取项目模板总路径
        /// </summary>
        public static string TemplatePath_Projects
        {
            get { return AddIn_SetUpPath + "Templates\\Projects\\"; }
        }

        /// <summary>
        /// 生成数据层类的项目的名称
        /// </summary>
        public static string ProjectName_Class = "RuleCode";

        /// <summary>
        /// 生成窗体的项目的名称
        /// </summary>
        public static string ProjectName_Form = "";

        /// <summary>
        /// 生成Web的项目的名称
        /// </summary>
        public static string ProjectName_WebForm = "";
        #endregion

        #region 插件对象属性
        /// <summary>
        /// 获取或设置插件对象
        /// </summary>
        public static  DTE AddIn_ApplicationObject
        {
            get;
            set;
        }

        #endregion

        #region 文件拷贝辅助方法
        /// <summary>
        /// 把某个单个文件添加到项目的更目录下面，若原来就存在，则覆盖
        /// </summary>
        /// <param name="project"></param>
        /// <param name="fileName"></param>
        public static void AddFile(EnvDTE.Project project, string fileName)
        {
            if (project == null)
                return;
            if (!File.Exists(fileName))
            {
                Util.SetStatusInfo("文件:"+fileName +"  不存在！");
                return;
            }

            FileInfo fInfo = new FileInfo(fileName);
            string fName = fInfo.Name;
            EnvDTE.ProjectItem projectItem = null;
            string newFileName = Directory.GetParent(project.FileName).FullName + "\\" + fName;
            File.Copy(fileName, newFileName, true);  //先复制，在添加到项目中
            try
            {
                projectItem = project.ProjectItems.Item(fName);
            }
            catch { }
            if (projectItem == null)  //如果不存在
                project.ProjectItems.AddFromFileCopy(newFileName);
            project.Save(project.FullName);
        }

        /// <summary>
        /// 把某个单个文件添加到项目项的下面，若原来就存在，则覆盖
        /// </summary>
        /// <param name="projectItem"></param>
        /// <param name="fileName"></param>
        public static void AddFile(EnvDTE.ProjectItem projectItem, string fileName)
        {
            if (projectItem == null)
                return;
            if (!File.Exists(fileName))
            {
                Util.SetStatusInfo("文件:" + fileName + "  不存在！");
                return;
            }

            EnvDTE.Project project = projectItem.ContainingProject;
            FileInfo fInfo = new FileInfo(fileName);
            string fName = fInfo.Name;
            string newFileName = projectItem.get_FileNames(1) + fName;
            if(fileName.ToLower () != newFileName.ToLower ( ))
                File.Copy(fileName, newFileName, true);  //先复制，在添加到项目中  
            EnvDTE.ProjectItem childItem = null;
            try
            {
                childItem = projectItem.ProjectItems.Item(fName);    
            }
            catch { }
            
            if (childItem == null)  //如果不存在
                projectItem.ProjectItems.AddFromFile(newFileName);
            
            project.Save(project.FullName);
        }

        /// <summary>
        /// 把某个单个文件夹添加到项目的子项的目录下面，若原来就存在，则覆盖
        /// </summary>
        /// <param name="project"></param>
        /// <param name="filePath"></param>
        public static void AddPath(EnvDTE.Project project, string filePath)
        {
            if (project  == null)
                return;
            if (!Directory.Exists(filePath))
            {
                Util.SetStatusInfo("文件路径:" + filePath + "  不存在！");
                return;
            }
            try
            {
                string sourceDirectory = filePath;
                if (Directory.Exists(sourceDirectory))
                {
                    DirectoryInfo sourceDirectInfo = new DirectoryInfo(sourceDirectory);
                    sourceDirectory = sourceDirectInfo.FullName; //避免出现 "D:\\a\\"最后的斜杆
                    string destinDirectory = Directory.GetParent(project.FileName).FullName + "\\" + sourceDirectInfo.Name;

                    if (!Directory.Exists(destinDirectory))
                        Directory.CreateDirectory(destinDirectory);

                    EnvDTE.ProjectItem childItem = null;
                    try
                    {
                        childItem = project.ProjectItems.Item(sourceDirectInfo.Name);
                    }
                    catch { }
                    if (childItem == null)
                        childItem = project.ProjectItems.AddFromDirectory(destinDirectory);//, EnvDTE.Constants.vsProjectItemKindPhysicalFolder);

                    FileInfo[] childSourceFileInfos = sourceDirectInfo.GetFiles();
                    foreach (FileInfo childFileInfo in childSourceFileInfos)
                    {
                        string newFileName = destinDirectory + "\\" + childFileInfo.Name;
                        AddFile(childItem, childFileInfo.FullName);
                    }
                    DirectoryInfo[] childSourceDirectInfos = sourceDirectInfo.GetDirectories();
                    foreach (DirectoryInfo childDInfo in childSourceDirectInfos)
                    {
                        string newDirectory = destinDirectory + "\\" + childDInfo.Name;
                        AddPath(childItem, childDInfo.FullName);
                    }
                }
            }
            catch { };

            project.Save(project.FileName);
        }


        /// <summary>
        /// 把某个单个文件夹添加到项目的子项的目录下面，若原来就存在，则覆盖
        /// </summary>
        /// <param name="projectItem"></param>
        /// <param name="filePath"></param>
        public static void AddPath(EnvDTE.ProjectItem projectItem, string filePath)
        {
            if (projectItem == null)
                return;
            if (!Directory.Exists(filePath))
            {
                Util.SetStatusInfo("文件路径:" + filePath + "  不存在！");
                return;
            }
            try
            {
                string sourceDirectory = filePath;
                if (Directory.Exists(sourceDirectory))
                {
                    DirectoryInfo sourceDirectInfo = new DirectoryInfo(sourceDirectory);
                    sourceDirectory = sourceDirectInfo.FullName; //避免出现 "D:\\a\\"最后的斜杆
                    string destinDirectory = projectItem.get_FileNames(1) + sourceDirectInfo.Name;

                    if (!Directory.Exists(destinDirectory))
                        Directory.CreateDirectory(destinDirectory);

                    EnvDTE.ProjectItem childItem = null;
                    try
                    {
                        childItem = projectItem.ProjectItems.Item(sourceDirectInfo.Name);
                    }
                    catch { }
                    if (childItem == null)
                        childItem = projectItem.ProjectItems.AddFromDirectory(destinDirectory);//, EnvDTE.Constants.vsProjectItemKindPhysicalFolder);

                    FileInfo[] childSourceFileInfos = sourceDirectInfo.GetFiles();
                    foreach (FileInfo childFileInfo in childSourceFileInfos)
                    {
                        string newFileName = destinDirectory + "\\" + childFileInfo.Name;
                        AddFile(childItem, childFileInfo.FullName);
                    }
                    DirectoryInfo[] childSourceDirectInfos = sourceDirectInfo.GetDirectories();
                    foreach (DirectoryInfo childDInfo in childSourceDirectInfos)
                    {
                        string newDirectory = destinDirectory + "\\" + childDInfo.Name;
                        AddPath(childItem, childDInfo.FullName);
                    }
                }
            }
            catch { };

            projectItem.ContainingProject.Save(projectItem.ContainingProject.FileName);
        }
        #endregion

        #region 查找项目和项目项
        /// <summary>
        /// 根据项目树中节点的路径获取相关项目项，路径格式为：a\\b\\...\\c\\    
        /// </summary>
        /// <param name="project">项目树中节点所在的项目</param>
        /// <param name="nodePath">项目树中节点的路径格式为：a\\b\\...\\c\\</param>
        /// <returns></returns>
        public static ProjectItem FindProjectItem(Project project, string nodePath)
        {
            if (project == null || nodePath.Trim() == string.Empty)
                return null;

            ProjectItem item = null;
            ProjectItems allParentItems = project.ProjectItems ;
            string[] allNodeNames = nodePath.Trim().Trim("\\".ToCharArray()).Split("\\".ToCharArray());
            for (int i = 0; i < allNodeNames.Length; i++)
            {
                if (allNodeNames[i].Trim() != string.Empty)
                {
                    item = null;       
                    for (int j=1;j<=allParentItems.Count;j++)
                    {
                        if (allParentItems.Item (j).Name == allNodeNames[i])
                        {
                            item = allParentItems.Item(j);
                            break;
                        }
                    }
                    if (item == null)
                        return null;
                    allParentItems = item.ProjectItems;
                }
                else {
                    return null;
                }
            }
            return item;
        }

        /// <summary>
        /// 创建文件夹，如果有的话，返回元文件夹项，没有的话，则创建！
        /// </summary>
        /// <param name="project">创建文件夹的项目</param>
        /// <param name="nodePath">文件夹路径</param>
        /// <returns></returns>
        public static ProjectItem CreateProjectItem(Project project, string nodePath)
        {
            if (project == null || nodePath.Trim() == string.Empty)
                return null;

            //物理路径
            string phyFullPath = string.Empty;
            FileInfo projectInfo = new FileInfo(project.FullName);
            phyFullPath = projectInfo.DirectoryName;

            ProjectItem item = null;
            ProjectItems allParentItems = project.ProjectItems;
            string[] allNodeNames = nodePath.Trim().Trim("\\".ToCharArray()).Split("\\".ToCharArray());
            for (int i = 0; i < allNodeNames.Length; i++)
            {
                if (allNodeNames[i].Trim() != string.Empty)
                {
                    phyFullPath = Path.Combine(phyFullPath, allNodeNames[i]);

                    item = null;
                    for (int j = 1; j <= allParentItems.Count; j++)
                    {
                        if (allParentItems.Item(j).Name == allNodeNames[i])
                        {
                            item = allParentItems.Item(j);
                            break;
                        }
                    }
                    if (item == null)
                    {
                        try                   
                        {
                            if (!Directory.Exists(phyFullPath))
                                item = allParentItems.AddFolder(allNodeNames[i], Constants.vsProjectItemKindPhysicalFolder);
                            else
                                item = allParentItems.AddFromDirectory(phyFullPath);
                            project.Save(project.FullName);
                        }
                        catch (Exception error)
                        {
                            Util.SetStatusInfo(error.Message);
                            return null;
                        }
                    }
                    allParentItems = item.ProjectItems;
                }
                else
                {
                    return null;
                }
            }
            return item;
        }

        ///// <summary>
        ///// 查找或创建项目项。，如果有的话，就返回该项目项；否则，则创建新的项目项；
        ///// </summary>
        ///// <param name="project"></param>
        ///// <param name="itemPath"></param>
        ///// <returns></returns>
        //public static ProjectItem FindOrCreateProjectItem(Project project, string itemPath)
        //{
        //    ProjectItem projectItem = null;
            
        //}

        /// <summary>
        /// 根据项目名称查找项目
        /// </summary>
        /// <param name="projectName">项目名称</param>
        /// <returns></returns>
        public static Project FindProject(string projectName)
        {
            Project project = null;
            if (AddIn_ApplicationObject != null)
            {
                try
                {
                    for (int i = 1; i <= AddIn_ApplicationObject.Solution.Projects.Count; i++)
                    {
                        if (AddIn_ApplicationObject.Solution.Projects.Item(i).Name == projectName)
                        {
                            project = AddIn_ApplicationObject.Solution.Projects.Item(i);
                            break;
                        }
                    }                                                                       
                }
                catch (Exception e)
                {
                    AddIn_ApplicationObject.StatusBar.Text = e.Message;
                }
            }
            else
            {
                MessageBox.Show("对不起，插件尚未加载成功！");
            }
            
            return project;
        }  
        #endregion

        #region 路径辅助方法
        /// <summary>
        /// 获取生成文件目录 ，包括"\\"
        /// </summary>
        /// <param name="generateFileType">生成文件的类型</param>
        /// <returns></returns>
        public static string GetGeneratorFileDirectory(GenerateFileType generateFileType)
        {
            string filePath = string.Empty;
            switch (generateFileType)
            {
                case GenerateFileType.Class:
                    {
                        filePath = Util.GetClassPath +"\\";
                        break ;
                    }
                case GenerateFileType.Enum :
                    {
                        filePath =Util.GetEnumsPath  + "\\";
                        break;
                    }
                case GenerateFileType.ExtendDataType :
                    {
                        filePath = Util.GetExtendDateTypesPath  + "\\";
                        break;
                    }
                case GenerateFileType.Table :
                    {
                        filePath = Util.GetTablesPath  + "\\";
                        break;
                    }
                case GenerateFileType.TableField :
                    {
                        filePath = Util.GetTableFieldsPath  + "\\";
                        break;
                    }
                case GenerateFileType.Query:
                    {
                        filePath = Util.GetQueriesPath  + "\\";
                        break;
                    }
                case GenerateFileType.Form:
                    {
                        filePath = Util.GetFormsPath  + "\\";
                        break;
                    }
                case GenerateFileType.WebForm:
                    {
                        filePath = Util.GetWebFormsPath + "\\";
                        break;
                    }
                default :
                    break;

            }
            return filePath;
        }

                         
        /// <summary>
        ///  获取项目项的节点路径录 ，包括"\\"，一般用于转移文件至项目中有用
        /// </summary>
        /// <param name="generateFileType">生成文件的类型</param>
        /// <returns></returns>
        public static string GetProjectItemNodePath(GenerateFileType generateFileType)
        {
            string filePath = string.Empty;
            switch (generateFileType)
            {
                case GenerateFileType.Class:
                    {
                        filePath =BasePath_ClassFile + GlobalFolderNameInProject .Classes +"\\";
                        break;
                    }
                case GenerateFileType.Enum:
                    {
                        filePath = BasePath_ClassFile + GlobalFolderNameInProject.Enums  + "\\";
                        break;
                    }
                case GenerateFileType.ExtendDataType:
                    {
                        filePath = BasePath_ClassFile + GlobalFolderNameInProject.Exts  + "\\";
                        break;
                    }
                case GenerateFileType.Table:
                    {
                        filePath = BasePath_ClassFile + GlobalFolderNameInProject.Tables  + "\\";
                        break;
                    }
                case GenerateFileType.TableField:
                    {
                        filePath = BasePath_ClassFile + GlobalFolderNameInProject.TableFields  + "\\";
                        break;
                    }

                case GenerateFileType.Query:
                    {
                        filePath = BasePath_ClassFile + GlobalFolderNameInProject.Queries  + "\\";
                        break;
                    }
                case GenerateFileType.Form:    //需要修改
                    {
                        filePath = BasePath_FormFile + GlobalFolderNameInProject.Forms  + "\\";
                        break;
                    }
                case GenerateFileType.WebForm:    //需要修改
                    {
                        filePath = BasePath_WebFile + GlobalFolderNameInProject.WebForms   + "\\";
                        break;
                    }
                default:
                    break;

            }
            return filePath;
        }
        #endregion

        #region 转移文件操作
        /// <summary>
        /// 把生成的源文件 添加到相关项目的节点路径下
        /// </summary>
        /// <param name="project">要添加文件的项目</param>
        /// <param name="generateFileType">生成源文件类型</param>
        /// <param name="sourceFileName">生成源文件的FullName</param>
        /// <param name="nodePath">将要添加的节点的路径</param>
        public  static void AddGeneratedFileToProject(Project project, string nodePath, string sourceFileName)
        {
            if (AddIn_ApplicationObject != null && AddIn_ApplicationObject.Solution.Count > 0)
            {
                ProjectItem parentItem = CreateProjectItem (project, nodePath);
                if(parentItem !=null)
                    AddFile(parentItem, sourceFileName);
            }
        }
                

        /// <summary>
        /// 添加生成的文件到项目中
        /// </summary>
        /// <param name="treeNode"></param>
        /// <param name="generateFileType"></param>
        public static void AddGeneratedFileToProject(SysTreeNode treeNode, GenerateFileType generateFileType)
        {
            if (AddIn_ApplicationObject != null && AddIn_ApplicationObject.Solution.Count > 0)
            {
                
                string nodePath = string.Empty;
                string sourceFileFullName = string.Empty;
                Project project = null;
                Struct_GenerateTypePathProject gStruct = AllGenerateTypePathProjects[generateFileType];
                project = gStruct.Project;
                nodePath = gStruct.GeneratePath;
                //生成数据层类的代码
                if (generateFileType == GenerateFileType.Class || generateFileType == GenerateFileType.Enum || generateFileType == GenerateFileType.ExtendDataType
                    || generateFileType == GenerateFileType.Table || generateFileType == GenerateFileType.TableField)
                {                               
                    sourceFileFullName = GetGeneratorFileDirectory(generateFileType);
                    if (generateFileType == GenerateFileType.TableField)
                    {
                        string tableName = treeNode.Parent.Parent.Text;
                        sourceFileFullName += tableName + "_" + treeNode.Text + ".cs";
                    }
                    else if (generateFileType == GenerateFileType.Table)
                    {
                        sourceFileFullName += treeNode.Text + ".Designer.cs";
                    }
                    else
                    {
                        sourceFileFullName += treeNode.Text + ".cs";
                    }                                        
                    AddGeneratedFileToProject(project, nodePath, sourceFileFullName);

                    //增加PartialTable文件
                    if (generateFileType == GenerateFileType.Table)
                    {
                        string partialTableFullName = Path.Combine ( Util.GetPartialTablesPath, treeNode .Text +".cs");
                        string partialTableProjectPath = string.Empty;
                        if (String.IsNullOrEmpty(nodePath))
                        {
                            partialTableProjectPath = GlobalStaticDirectoryPath .PartialTables ;
                        }
                        else
                        {
                            string newNodePath = nodePath.Trim().Trim("\\".ToCharArray());
                            int index = newNodePath.LastIndexOf("\\");
                            if (index < 0)
                                partialTableProjectPath = GlobalStaticDirectoryPath.PartialTables;
                            else
                                partialTableProjectPath = newNodePath.Substring(0, index + 1) + GlobalStaticDirectoryPath.PartialTables;
                        }
                        ProjectItem partialItem = CreateProjectItem(project, partialTableProjectPath);
                        if (partialItem != null && File.Exists(partialTableFullName))
                        {                                  
                            ProjectItem ptableItem = null;
                            for(int i=1;i<=partialItem.ProjectItems.Count ;i++)
                            {
                                if (partialItem.ProjectItems.Item(i).Name.ToLower() == (treeNode.Text + ".cs").ToLower())
                                {
                                    ptableItem = partialItem.ProjectItems.Item(i);
                                    break;
                                }
                            }

                            if(ptableItem ==null )
                                AddFile(partialItem, partialTableFullName);
                        }
                    }
                }
                else
                {
                    if (generateFileType == GenerateFileType.Query) //此时 treeNode有可能是表的节点，也有可能是 Query的节点，暂时只有前一种情况
                    {                                            
                        sourceFileFullName = GetGeneratorFileDirectory(generateFileType);  
                        string nodeType = string.Empty;
                        try
                        {
                            nodeType = treeNode.SysXmlNode.Attributes.GetNamedItem("Type").Value;
                        }
                        catch { }
                        if (nodeType == OT.Table)
                            sourceFileFullName += treeNode.Text + "_Query.cs";
                        else if (nodeType == OT.Query)
                            sourceFileFullName += treeNode.Text + ".cs";
                        else
                            return;   
                        AddGeneratedFileToProject(project, nodePath, sourceFileFullName);
                    }    
                }    
            }
        }

        /// <summary>
        /// 添加页面类型文件到项目中去
        /// </summary>
        /// <param name="project">相应的项目</param>
        /// <param name="path">项目中对应文件夹的路径</param>
        /// <param name="pageName">添加的页面文件的名称，包括整个绝对路径：例如：页面..\\..\\test.aspx则名称为：..\..\test</param>
        public  static void AddGeneratedFileToProject_WebForm(Project project, string path, string pageName)
        {
            try
            {
                string sourceFileFullName = string.Empty;
                sourceFileFullName = Path.Combine(Util.WebFormSingleOutputPath, pageName + ".aspx");
                AddGeneratedFileToProject(project, path, sourceFileFullName);
                sourceFileFullName = Path.Combine(Util.WebFormSingleOutputPath, pageName + ".aspx.cs");
                AddGeneratedFileToProject(project, path, sourceFileFullName);
                sourceFileFullName = Path.Combine(Util.WebFormSingleOutputPath, pageName + ".aspx.designer.cs");
                AddGeneratedFileToProject(project, path, sourceFileFullName);
            }
            catch (Exception error)
            {
                Util.SetStatusInfo(error.Message);
            }
        }

        /// <summary>
        /// 将生成好的WebForm窗体添加到相应的项目中；
        /// </summary>
        /// <param name="node">对象树的对应的WebForm的节点</param>
        /// <param name="type">项目文件夹的类型（或者名称）类似：OT.WebFormTrees</param>
        public static void AddGeneratedFileToProject_WebForm(SysTreeNode node,string type)
        {
            try
            {
                if (AddIn_ApplicationObject != null && AddIn_ApplicationObject.Solution.Count > 0)
                {
                    Util.SetProerptyInSilent(node);
                    string nodePath = string.Empty;
                    string sourceFileFullName = string.Empty;
                    Project project = null;
                    Struct_GenerateTypePathProject gStruct = AllGenerateTypePathProjects[GenerateFileType .WebForm ];
                    project = gStruct.Project;
                    nodePath = gStruct.GeneratePath.TrimEnd ("\\".ToCharArray ());  
                    nodePath = Path.Combine(nodePath, type);
                    string nodeName =node .Text ;

                    switch (type)
                    {
                        case OT.WebFormTrees:
                            {                                                 
                                break;
                            }
                        case OT.WebFormSingles:
                            {      
                                string TableName = ((WebFormSingleProperty)node.Property).Table;
                                sourceFileFullName = Path.Combine(Util.WebFormSingleOutputPath, TableName + "_List").TrimEnd ("\\".ToCharArray ());
                                AddGeneratedFileToProject_WebForm(project, nodePath, sourceFileFullName);
                                sourceFileFullName = Path.Combine(Util.WebFormSingleOutputPath, TableName + "_Edit").TrimEnd("\\".ToCharArray());
                                AddGeneratedFileToProject_WebForm(project, nodePath, sourceFileFullName);
                                break;
                            }
                        case OT.WebFormRelations:
                            {
                                break;
                            }
                        case OT.WebFormParameters:
                            {
                                break;
                            }
                        case OT.WebFormParaByUsers:
                            {
                                break;
                            }
                        case OT.WebFormMasterSlaves:
                            {
                                string MasterTableName = ((WebFormMasterSlaveProperty)node.Property).Table;
                                break;
                            }
                        default:
                            break;
                    }
                }
            }
            catch (Exception error)
            {
                Util.SetStatusInfo(error.Message);
            }
        }

        /// <summary>
        /// 删除项目中的文件项
        /// </summary>
        /// <param name="project"></param>
        /// <param name="fileName">相对文件路径</param>
        public static void DeleteFileInProject(Project project, string fileName)
        {
            try
            {
                ProjectItem item = FindProjectItem(project, fileName);
                if (item != null)
                {
                    item.Delete();
                    project.Save(project.FullName);
                }
            }
            catch (Exception error)
            {
                Util.SetStatusInfo(error .Message );
            }
        }        

        /// <summary>
        /// 删除节点对应在项目中的文件
        /// </summary>
        /// <param name="node"></param>
        public static void DeleteGeneratedFile( SysTreeNode node)
        {
            Util.SetProerptyInSilent(node);
            string type = string.Empty;
            try
            {
                type = node.SysXmlNode.Attributes.GetNamedItem("Type").Value;
            }
            catch { }
            GenerateFileType generateFileType = GenerateFileType.Class;
            switch (type)
            {
                case OT.Class :
                    {
                        generateFileType = GenerateFileType.Class;
                        break;
                    }
                case OT.BaseEnum  :
                    {
                        generateFileType = GenerateFileType.Enum ;
                        break;
                    }
                case OT.ExtendDataType:
                    {
                        generateFileType = GenerateFileType.ExtendDataType ;
                        break;
                    }
                case OT.Table :
                    {
                        generateFileType = GenerateFileType.Table ;
                        break;
                    }
                case OT.TableField :
                    {
                        generateFileType = GenerateFileType.TableField ;
                        break;
                    }
                case OT.Query:
                    {
                        generateFileType = GenerateFileType.Query;
                        break;
                    }
                case OT.Form:
                    {
                        generateFileType = GenerateFileType.Form;
                        break;
                    }
                default: 
                    return;
            }
            if (AddIn_ApplicationObject != null && AddIn_ApplicationObject.Solution.Count > 0)
            {

                Struct_GenerateTypePathProject generateTypeProject = AllGenerateTypePathProjects[generateFileType];
                if (generateTypeProject.Project == null)
                    return;

                string projectName = string.Empty;
                string nodePath0 = generateTypeProject.GeneratePath.Trim ("\\".ToCharArray ())+"\\";
                string nodePath = generateTypeProject.GeneratePath.Trim("\\".ToCharArray()) + "\\";
                //projectName = ProjectName_Class;
                //生成数据层类的代码
                if (generateFileType == GenerateFileType.Class || generateFileType == GenerateFileType.Enum || generateFileType == GenerateFileType.ExtendDataType
                    || generateFileType == GenerateFileType.Table || generateFileType == GenerateFileType.TableField)
                {
                    if (generateFileType == GenerateFileType.TableField)
                    {
                        string tableName = node.Parent.Parent.Text;
                        nodePath  += tableName + "_" + node.Text + ".cs";
                    }
                    else if (generateFileType == GenerateFileType.Table)
                    {
                        nodePath += node.Text + ".Designer.cs";
                    }
                    else
                    {
                        nodePath += node.Text + ".cs";
                    }

                    try
                    {
                        Project project = generateTypeProject .Project ;
                        ProjectItem item = FindProjectItem(project, nodePath);
                        if (item != null)
                            item.Delete();

                        //删除PartialTable文件
                        if (generateFileType == GenerateFileType.Table)
                        {
                            string partialTableProjectPath = string.Empty;
                            if (String.IsNullOrEmpty(nodePath0))
                            {
                                partialTableProjectPath = GlobalStaticDirectoryPath.PartialTables;
                            }
                            else
                            {
                                string newNodePath = nodePath0.Trim().Trim("\\".ToCharArray());
                                int index = newNodePath.LastIndexOf("\\");
                                if (index < 0)
                                    partialTableProjectPath = GlobalStaticDirectoryPath.PartialTables;
                                else
                                    partialTableProjectPath = newNodePath.Substring(0, index + 1) + GlobalStaticDirectoryPath.PartialTables;
                            }

                            ProjectItem partialItem = FindProjectItem(project, partialTableProjectPath.TrimEnd("\\".ToCharArray ())+"\\"+node.Text + ".cs");
                            if (partialItem != null)
                                partialItem.Delete();
                        }

                        project.Save(project.FullName);
                    }
                    catch (Exception e)
                    {
                        Util.SetStatusInfo(e.Message);
                    }
                }
                else
                {
                    if (generateFileType == GenerateFileType.Query) //此时 treeNode有可能是表的节点，也有可能是 Query的节点，暂时只有前一种情况
                    {
                        string nodeType = string.Empty;
                        try
                        {
                            nodeType = node.SysXmlNode.Attributes.GetNamedItem("Type").Value;
                        }
                        catch { }
                        if (nodeType == OT.Table)
                            nodePath += node.Text + "_Query.cs";
                        else if (nodeType == OT.Query)
                            nodePath += node.Text + ".cs";
                        else
                            return;

                        try
                        {
                            //projectName = ProjectName_Class ;
                            Project project = generateTypeProject.Project ;
                            ProjectItem item = FindProjectItem(project, nodePath);
                            if (item != null)
                                item.Delete();
                            project.Save(project.FullName);
                        }
                        catch (Exception e)
                        {
                            Util.SetStatusInfo(e.Message );
                        }
                    }         
                }    
                                 
            }
        }
        #endregion

        #region 文件查找操作
        /// <summary>
        /// 查找目录下所有符合要求的文件
        /// </summary>
        /// <param name="path"></param>
        /// <param name="searchPattern"></param>
        /// <returns></returns>
        public static FileInfo[] SearchFiles(string path, string searchPattern)
        {
            List<FileInfo> allFileInfos = new List<FileInfo>();
            DirectoryInfo dInfo = new DirectoryInfo(path);
            if (dInfo.Exists)
            {
                FileInfo[] childFInfos = dInfo.GetFiles(searchPattern);
                allFileInfos.AddRange(childFInfos);
                DirectoryInfo[] childDInfos = dInfo.GetDirectories();
                foreach (DirectoryInfo DINFOS in childDInfos)
                {
                    allFileInfos.AddRange (SearchFiles (DINFOS.FullName ,searchPattern ));
                }
            }
            return allFileInfos.ToArray();

        }
        #endregion


        #region 配置相关
        public  static Dictionary<GenerateFileType, Struct_GenerateTypePathProject> _AllGenerateTypePathProjects;
        /// <summary>
        /// 获取或设置 当前的所有生成代码路以及对应的
        /// </summary>
        public static Dictionary<GenerateFileType, Struct_GenerateTypePathProject> AllGenerateTypePathProjects
        {
            get {
                if (_AllGenerateTypePathProjects == null)
                    Util.InitCurrentProfileName();
                return _AllGenerateTypePathProjects;
            }
            set
            {
                _AllGenerateTypePathProjects = value;
            }
        }
        /// <summary>
        /// 获取 生成代码的路径和项目
        /// </summary>
        /// <param name="solutionNode"></param>
        /// <param name="generateFileType"></param>
        /// <returns></returns>
        public static Struct_GenerateTypePathProject GetGenerateTypePathProjectStrct(XmlNode solutionNode,GenerateFileType generateFileType,string solutionNodeFilter)
        {
            string nodeName = string.Empty;
            switch (generateFileType)
            {                
                case GenerateFileType.Class :
                    nodeName = "//Classes";
                    break;
                case GenerateFileType.Enum :
                    nodeName = "//Enums";
                    break;
                case GenerateFileType.ExtendDataType :
                    nodeName = "//ExtendDataTypes";
                    break;       
                case GenerateFileType.Form :
                    nodeName = "//Forms";
                    break;
                case GenerateFileType.Query :
                    nodeName = "//Queries";
                    break;
                case GenerateFileType.Table :
                    nodeName = "//Tables";
                    break;
                case GenerateFileType.TableField :
                    nodeName = "//TableFields";
                    break;
                case GenerateFileType.WebForm :
                    nodeName = "//WebForms";
                    break;
                default:
                    break;
            }
            XmlNode pathNode = solutionNode.SelectSingleNode(solutionNodeFilter+nodeName);
            Struct_GenerateTypePathProject GenerateTypePathProject = new Struct_GenerateTypePathProject();
            string path = pathNode.Attributes.GetNamedItem("Value").Value;
            string projectName = pathNode.Attributes.GetNamedItem("Project").Value;
            GenerateTypePathProject.GeneratePath = path;
            GenerateTypePathProject.Project = Util_DTE.FindProject(projectName);
            return GenerateTypePathProject;
        }
         
        #endregion
    }
    #endregion   

    #region 辅助枚举和类
    /// <summary>
    /// 生成文件类型
    /// </summary>
    public enum GenerateFileType
    {               

        /// <summary>
        /// 具体的表名
        /// </summary>
        Table,

        /// <summary>
        /// 字段
        /// </summary>
        TableField,

        /// <summary>
        /// 扩展类型
        /// </summary>
        ExtendDataType,

        /// <summary>
        /// 枚举
        /// </summary>
        Enum,

        /// <summary>
        /// 类
        /// </summary>
        Class,

        /// <summary>
        /// Query查询结构
        /// </summary>
        Query,

        /// <summary>
        /// C/S 窗体
        /// </summary>
        Form,

        /// <summary>
        /// W/S 页面
        /// </summary>
        WebForm
    }


    /// <summary>
    /// 用于存放生成代码文件的文件夹的名称
    /// </summary>
    public class GlobalFolderNameInProject
    {

        /// <summary>
        /// 存放Classes代码文件的文件夹
        /// </summary>
        public static string Classes = "Classes";

        /// <summary>
        /// 存放Table代码文件的文件夹
        /// </summary>
        public static string Tables = "Tables";

        /// <summary>
        /// 存放TableFields代码文件的文件夹
        /// </summary>
        public static string TableFields = "TableFields";

        /// <summary>
        /// 存放Queries代码文件的文件夹
        /// </summary>
        public static string Queries = "Queries";

        /// <summary>
        /// 存放PartialTables代码文件的文件夹
        /// </summary>
        public static string PartialTables = "PartialTables";

        /// <summary>
        /// 存放Exts代码文件的文件夹
        /// </summary>
        public static string Exts = "Exts";

        /// <summary>
        /// 存放Enums代码文件的文件夹
        /// </summary>
        public static string Enums = "Enums";

        /// <summary>
        /// 存放Webs代码文件的文件夹
        /// </summary>
        public static string WebForms = "Webs";

        /// <summary>
        /// 存放Forms代码文件的文件夹
        /// </summary>
        public static string Forms = "Forms";

    }

    public struct Struct_GenerateTypePathProject
    {                                                          

        public  Project Project { get; set; }

        public string GeneratePath { get; set; }
    }

    /// <summary>
    /// 用于文件版本控制的枚举类型，主要是 AOTFile,LabelFile
    /// </summary>
    public enum FileVersionType
    {
        AOTFile =0,

        LabelFile 
    }
    #endregion

}
